package com.gzhryc.shared_device.oem.h5.mng.controllers.device;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.excel.ExcelTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.bxscn.code.BXSCNProduceConfig;
import com.gzhryc.shared_device.cdb.code.CDBProduceConfig;
import com.gzhryc.shared_device.cdcz.code.CDCZProduceConfig;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.dao.db.DeviceProduceBatch;
import com.gzhryc.shared_device.common.device.dao.db.DeviceType;
import com.gzhryc.shared_device.common.device.dao.db.DeviceTypeFunc;
import com.gzhryc.shared_device.common.device.dao.enums.DeviceProduceBatchEnum;
import com.gzhryc.shared_device.common.device.services.DeviceProduceBatchService;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeFuncService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeService;
import com.gzhryc.shared_device.common.device.services.dto.DeviceProduceBatchSearch;
import com.gzhryc.shared_device.common.device.services.dto.DeviceSearch;
import com.gzhryc.shared_device.iot.code.dao.db.IOTServerNode;
import com.gzhryc.shared_device.iot.code.services.IOTServerNodeService;
import com.gzhryc.shared_device.oem.code.device.DeviceProduceBatchManager;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.shared_device.pcl.code.PCLProduceConfig;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DeviceProduceBatchController {

    static Logger log = Logger.getLogger(DeviceProduceBatchController.class);

    @Route(value = { "/device/produce/batch/list.html" })
    public String list(HttpServletRequest request) {
        request.setAttribute("stateList", DeviceProduceBatchEnum.State.values());
        return "/device/produce/batch/list.html";
    }

    @Route(value = "/device/produce/batch/list.data")
    public ListResult<DeviceProduceBatch> listData(HttpServletRequest request) {
        ListResult<DeviceProduceBatch> result = new ListResult<>(DtoConstants.NULL_DATA,"暂无数据");
        try {
            DeviceProduceBatchSearch search = WebUtils.getParameter(request, DeviceProduceBatchSearch.class);
            Integer pageNo = WebUtils.getInteger(request, "page", 1);
            Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
            String searchDate = WebUtils.getString(request, "searchDate");
            if (StringUtils.isNotBlank(searchDate)) {
                String[] strings = searchDate.split(" - ");
                if (strings.length == 2) {
                    Date startDate = DateUtils.parseDate(strings[0], "yyyy-MM-dd");
                    Date endDate = DateUtils.parseDate(strings[1], "yyyy-MM-dd");
                    search.setStartDate(startDate);
                    search.setEndDate(endDate);
                }
            }

            result.getBody().setTotal(DeviceProduceBatchService.self().countBySearch(search));
            result.getBody().setData(DeviceProduceBatchService.self().findBySearch(search, pageNo, pageLimit));

            if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
                result.setCode(DtoConstants.SUCCESS,null);
            }
        }catch (ParseException e){
            log.error(e.getMessage(),e);
            result.setMsg("查询时间解析失败");
        }
        return result;
    }

    @Route(value = { "/device/produce/batch/info.html" })
    public String info(HttpServletRequest request) {
        String batchId = WebUtils.getString(request,"batchId");
        if(StringTools.isNotBlank(batchId)) {
            DeviceProduceBatch produceBatch = DeviceProduceBatchService.self().getJoinById(batchId);
            WebUtils.setAttribute(request, produceBatch);
        }
        return "/device/produce/batch/info.html";
    }

    @Route(value = { "/device/produce/batch/add.html" })
    public String add(HttpServletRequest request) {
        return "/device/produce/batch/edit.html";
    }

    @Route(value = { "/device/produce/batch/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增设备生产批次失败");
        String deviceTypeId = WebUtils.getString(request,"deviceTypeId");
        Integer startNum = WebUtils.getInteger(request,"startNum");
        Integer produceTotal = WebUtils.getInteger(request,"produceTotal");
        if(StringTools.isNotBlank(deviceTypeId) && startNum != null || produceTotal != null) {
            if(startNum < 1){
                result.setMsg("起始位必须大于等于1");
                return result;
            }
            if(produceTotal < 1 || produceTotal > 9999){
                result.setMsg("生产数量只能设置1-9999");
                return result;
            }

            DeviceType deviceType = DeviceTypeService.self().getById(deviceTypeId);
            if(deviceType == null) {
                result.setMsg("未找到设备类型");
                return result;
            }

            try {
                if (DeviceProduceBatchService.self().add(deviceType, startNum, produceTotal)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }else {
            result.setMsg("参数错误");
        }
        return result;
    }

    @Route(value = { "/device/produce/batch/update.html" })
    public String update(HttpServletRequest request) {
        String batchId = WebUtils.getString(request,"batchId");
        DeviceProduceBatch produceBatch = DeviceProduceBatchService.self().getJoinById(batchId);
        if(produceBatch != null) {
            WebUtils.setAttribute(request, produceBatch);
            List<DeviceTypeFunc> deviceTypeFuncList = DeviceTypeFuncService.self().findByTypeId(produceBatch.getDeviceTypeId());
            if(deviceTypeFuncList != null && deviceTypeFuncList.size() > 0) {
                request.setAttribute("deviceTypeFuncList", deviceTypeFuncList);
            }
        }
        return "/device/produce/batch/edit.html";
    }

    @Route(value = { "/device/produce/batch/update.do" })
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改设备生产批次失败");
        String batchId = WebUtils.getString(request,"batchId");
        String name = WebUtils.getString(request,"name");
        Integer startNum = WebUtils.getInteger(request,"startNum");
        Integer produceTotal = WebUtils.getInteger(request,"produceTotal");
        if(StringTools.isNotBlank(batchId) && startNum != null || produceTotal != null) {
            if(startNum < 1){
                result.setMsg("起始位必须大于等于1");
                return result;
            }
            if(produceTotal < 1 || produceTotal > 9999){
                result.setMsg("生产数量只能设置1-9999");
                return result;
            }

            DeviceProduceBatch produceBatch = DeviceProduceBatchService.self().getJoinById(batchId);
            if(produceBatch == null) {
                result.setMsg("未找到生产批次信息");
                return result;
            }

            DeviceProduceBatch updateEntity = new DeviceProduceBatch();
            updateEntity.setBatchId(batchId);
            updateEntity.setName(name);
            updateEntity.setStartNum(startNum);
            updateEntity.setProduceTotal(produceTotal);

            try {
                if(DeviceProduceBatchService.self().updateNotNull(updateEntity)){
                    result.setCode(DtoConstants.SUCCESS,null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }else {
            result.setMsg("参数错误");
        }
        return result;
    }

    @Route(value = "/device/produce/batch/import.html")
    public String uploadExcel(HttpServletRequest request) {
        request.setAttribute("iotNodeList", IOTServerNodeService.self().findAllUnable());
        return "/device/produce/batch/import.html";
    }

    @Route(value = "/device/produce/batch/import.do")
    public AjaxResult doUploadExcel(HttpServletRequest request, FileItem file, HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "导入失败，请稍后再试！");
        String deviceTypeId = WebUtils.getString(request, "deviceTypeId");
        String batchId = WebUtils.getString(request,"batchId");
        Integer startNum = WebUtils.getInteger(request,"startNum");
        if(StringTools.isNotBlank(deviceTypeId) && StringTools.isNotBlank(batchId) && startNum != null) {
            try {
                if (startNum < 1) {
                    result.setMsg("起始位必须大于等于1");
                    return result;
                }

                DeviceType deviceType = DeviceTypeService.self().getById(deviceTypeId);
                if (deviceType == null) {
                    result.setMsg("未找到设备类型");
                    return result;
                }

                List<DeviceTypeFunc> deviceTypeFuncList = DeviceTypeFuncService.self().findByTypeId(deviceType.getId());
                if(deviceTypeFuncList == null || deviceTypeFuncList.size() <=0) {
                    result.setMsg(deviceType.getId() + "设备类型未配置功能项");
                    return result;
                }

                String deviceFunCodes = "";
                String deviceFunNames = "";
                for(DeviceTypeFunc deviceTypeFunc : deviceTypeFuncList) {
                    deviceFunCodes = deviceFunCodes + "," + deviceTypeFunc.getCode();
                    deviceFunNames = deviceFunNames + "," + deviceTypeFunc.getNote();
                }

                deviceFunCodes = deviceFunCodes.substring(1);
                deviceFunNames = deviceFunNames.substring(1);

                Workbook workbook = ExcelTools.readExcelToWorkbook(file.getName(), file.getInputStream());
                List<Map<String, Object>> list = ExcelTools.readExcel(workbook, new String[]{"deviceSn"}, 0, 1);
                if (list != null && list.size() > 0) {
                    List<Device> deviceList = new ArrayList<>();
                    for (Map<String, Object> map : list) {
                        Object deviceSn = map.get("deviceSn");
                        if (deviceSn != null) {
                            Device device = new Device();
                            device.setDeviceSn(deviceSn.toString());
                            device.setDeviceTypeId(deviceType.getId());
                            device.setDeviceTypeName(deviceType.getName());
                            device.setNetworkType(deviceType.getNetworkType());
                            device.setDeviceFunCodes(deviceFunCodes);
                            device.setDeviceFunNames(deviceFunNames);
                            device.setBatchId(batchId);
                            device.setCreateDate(new Date());
                            deviceList.add(device);
                        }
                    }
                    if (DeviceProduceBatchService.self().addByImport(deviceType, batchId, startNum, deviceList)) {
                        result.setCode(DtoConstants.SUCCESS,null);
                    }
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return result;
    }

    @Route(value = { "/device/produce/batch/create.do" })
    public AjaxResult doCreate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "生成设备失败");
        String batchId = WebUtils.getString(request,"batchId");
        if(StringTools.isNotBlank(batchId)) {
            DeviceProduceBatch produceBatch = DeviceProduceBatchService.self().getJoinById(batchId);
            if(produceBatch == null) {
                result.setMsg("未找到生产批次信息");
                return result;
            }
            try {
                if (DeviceProduceBatchService.self().produceDevice(produceBatch)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }else {
            result.setMsg("参数错误");
        }
        return result;
    }

    @Route(value = { "/device/produce/batch/relevance.html" })
    public String relevance(HttpServletRequest request) {
        String batchId = WebUtils.getString(request,"batchId");
        DeviceProduceBatch produceBatch = DeviceProduceBatchService.self().getJoinById(batchId);
        if(produceBatch != null) {
            WebUtils.setAttribute(request, produceBatch);
            List<DeviceTypeFunc> deviceTypeFuncList = DeviceTypeFuncService.self().findByTypeId(produceBatch.getDeviceTypeId());
            if(deviceTypeFuncList != null && deviceTypeFuncList.size() > 0) {
                request.setAttribute("deviceTypeFuncList", deviceTypeFuncList);
                Map<String, Object> configContent = new HashMap<>();
                if (StringTools.isNotBlank(produceBatch.getConfigContent())) {
                    configContent = JsonTools.fromJson(produceBatch.getConfigContent());
                }

                for(DeviceTypeFunc func : deviceTypeFuncList){
                    Object obj = configContent.get(func.getCode());
                    if(obj != null) {
                        Map item = Map.class.cast(obj);
                        if (EDeviceFunCode.CDCZ.index().equals(func.getCode())) {
                            CDCZProduceConfig config = new CDCZProduceConfig();
                            Object val = item.get("iotType");
                            if(val != null) {
                                config.setIotType(Integer.valueOf(val.toString()));
                            }
                            val = item.get("iotNodeId");
                            if(val != null) {
                                config.setIotNodeId(Long.valueOf(val.toString()));
                            }
                            request.setAttribute(func.getCode()+"Config",config);
                        }else if (EDeviceFunCode.CDB.index().equals(func.getCode())) {
                            CDBProduceConfig config = new CDBProduceConfig();
                            Object val = item.get("iotType");
                            if(val != null) {
                                config.setIotType(Integer.valueOf(val.toString()));
                            }
                            val = item.get("iotNodeId");
                            if(val != null) {
                                config.setIotNodeId(Long.valueOf(val.toString()));
                            }
                            request.setAttribute(func.getCode()+"Config",config);
                        }else if (EDeviceFunCode.BXSCN.index().equals(func.getCode())) {
                            BXSCNProduceConfig config = new BXSCNProduceConfig();
                            Object val = item.get("iotType");
                            if(val != null) {
                                config.setIotType(Integer.valueOf(val.toString()));
                            }
                            val = item.get("iotNodeId");
                            if(val != null) {
                                config.setIotNodeId(Long.valueOf(val.toString()));
                            }
                            request.setAttribute(func.getCode()+"Config",config);
                        }else if (EDeviceFunCode.PCL.index().equals(func.getCode())) {
                            PCLProduceConfig config = new PCLProduceConfig();
                            Object val = item.get("secretKey");
                            if(val != null) {
                                config.setSecretKey(val.toString());
                            }
                            request.setAttribute(func.getCode()+"Config",config);
                        }
                    }

                    if (EDeviceFunCode.CDCZ.index().equals(func.getCode()) || EDeviceFunCode.CDB.index().equals(func.getCode())
                            || EDeviceFunCode.BXSCN.index().equals(func.getCode())) {
                        request.setAttribute("iotNodeList", IOTServerNodeService.self().findAllUnable());
                    }
                }
            }
        }
        return "/device/produce/batch/relevance.html";
    }

    @Route(value = { "/device/produce/batch/relevance.do" })
    public AjaxResult doRelevance(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "生成设备失败");
        String batchId = WebUtils.getString(request,"batchId");
        if(StringTools.isNotBlank(batchId)) {
            DeviceProduceBatch produceBatch = DeviceProduceBatchService.self().getJoinById(batchId);
            if(produceBatch == null) {
                result.setMsg("未找到生产批次信息");
                return result;
            }
            List<DeviceTypeFunc> deviceTypeFuncList = DeviceTypeFuncService.self().findByTypeId(produceBatch.getDeviceTypeId());
            if(deviceTypeFuncList != null && deviceTypeFuncList.size() > 0) {
                Map<String, Object> configContent = new HashMap<>();
                for (DeviceTypeFunc func : deviceTypeFuncList) {
                    if (EDeviceFunCode.CDCZ.index().equals(func.getCode())) {
                        Long iotNodeId = WebUtils.getLong(request, "CDCZConfig.iotNodeId");
                        if (iotNodeId != null) {
                            IOTServerNode node = IOTServerNodeService.self().getById(iotNodeId);
                            if (node == null) {
                                result.setMsg("IOT节点不存在");
                                return result;
                            }
                            if (!node.getProtocolType().equals(func.getProtocolType())) {
                                result.setMsg("IOT节点协议与设备不一致");
                                return result;
                            }
                            CDCZProduceConfig config = new CDCZProduceConfig();
                            config.setIotType(node.getIotType());
                            config.setIotNodeId(node.getId());
                            configContent.put(func.getCode(), config);
                        }
                    }else if(EDeviceFunCode.CDB.index().equals(func.getCode())){
                        Long iotNodeId = WebUtils.getLong(request, "CDBConfig.iotNodeId");
                        if (iotNodeId != null) {
                            IOTServerNode node = IOTServerNodeService.self().getById(iotNodeId);
                            if (node == null) {
                                result.setMsg("IOT节点不存在");
                                return result;
                            }
                            if (!node.getProtocolType().equals(func.getProtocolType())) {
                                result.setMsg("IOT节点协议与设备不一致");
                                return result;
                            }
                            CDBProduceConfig config = new CDBProduceConfig();
                            config.setIotType(node.getIotType());
                            config.setIotNodeId(node.getId());
                            configContent.put(func.getCode(), config);
                        }
                    }else if (EDeviceFunCode.BXSCN.index().equals(func.getCode())) {
                        Long iotNodeId = WebUtils.getLong(request,"BXSCNConfig.iotNodeId");
                        if(iotNodeId != null){
                            IOTServerNode node = IOTServerNodeService.self().getById(iotNodeId);
                            if(node == null){
                                result.setMsg("IOT节点不存在");
                                return result;
                            }
                            if(!node.getProtocolType().equals(func.getProtocolType())){
                                result.setMsg("IOT节点协议与设备不一致");
                                return result;
                            }
                            BXSCNProduceConfig config = new BXSCNProduceConfig();
                            config.setIotType(node.getIotType());
                            config.setIotNodeId(node.getId());
                            configContent.put(func.getCode(),config);
                        }
                    }else if (EDeviceFunCode.PCL.index().equals(func.getCode())) {
                        String secretKey = WebUtils.getString(request,"PCLConfig.secretKey");
                        if(StringTools.isNotBlank(secretKey)){
                            PCLProduceConfig config = new PCLProduceConfig();
                            config.setSecretKey(secretKey);
                            configContent.put(func.getCode(),config);
                        }
                    }
                }

                try {
                    if(DeviceProduceBatchManager.self().createFuncDevice(produceBatch,deviceTypeFuncList,configContent)){
                        result.setCode(DtoConstants.SUCCESS,null);
                    }
                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
            }
        }else {
            result.setMsg("参数错误");
        }
        return result;
    }

    @Route(value = { "/device/produce/batch/belong/set.html" })
    public String setBelong(HttpServletRequest request) {
        String batchId = WebUtils.getString(request,"batchId");
        DeviceProduceBatch produceBatch = DeviceProduceBatchService.self().getJoinById(batchId);
        if(produceBatch != null) {
            WebUtils.setAttribute(request, produceBatch);
            request.setAttribute("setStartNum", produceBatch.getStartNum());
            request.setAttribute("setTotal", produceBatch.getProduceTotal());
        }
        return "/device/produce/batch/belong.html";
    }

    @Route(value = { "/device/produce/batch/belong/set.do" })
    public AjaxResult doSetBelong(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "设置归属失败");
        String batchId = WebUtils.getString(request,"batchId");
        Long userId = WebUtils.getLong(request,"userId");
        Integer setStartNum = WebUtils.getInteger(request, "setStartNum");
        Integer setTotal = WebUtils.getInteger(request, "setTotal");
        Integer strategyType = WebUtils.getInteger(request,"strategyType");
        if(StringTools.isNotBlank(batchId) && setStartNum != null && setTotal != null) {
            User user = UserService.self().getById(userId);
            if(user == null){
                result.setMsg("未找到用户信息");
                return result;
            }
            try {
                if(DeviceProduceBatchService.self().setBelong(batchId,user,strategyType,setStartNum,setTotal)){
                    result.setCode(DtoConstants.SUCCESS,null);
                    return result;
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }else {
            result.setMsg("参数错误");
        }
        return result;
    }

    @Route(value = { "/device/produce/batch/device/list.html" })
    public String deviceList(HttpServletRequest request) {
        String batchId = WebUtils.getString(request,"batchId");
        DeviceProduceBatch produceBatch = DeviceProduceBatchService.self().getJoinById(batchId);
        if(produceBatch != null) {
            WebUtils.setAttribute(request, produceBatch);
        }
        return "/device/produce/batch/device/list.html";
    }

    @Route(value = "/device/produce/batch/device/list.data")
    public ListResult<Device> deviceListData(HttpServletRequest request) {
        ListResult<Device> result = new ListResult<>(DtoConstants.NULL_DATA,"暂无数据");
        DeviceSearch search = WebUtils.getParameter(request, DeviceSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        if(StringTools.isNotBlank(search.getBatchId())) {
            result.getBody().setTotal(DeviceService.self().countBySearch(search));
            result.getBody().setData(DeviceService.self().findBySearch(search, pageNo, pageLimit));

            if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        }
        return result;
    }
    
    @Route(value = { "/device/produce/batch/device/belong/cache.do" })
    public AjaxResult doDeviceSetBelongCache(HttpServletRequest request,HttpSession session) {
    	 AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "设置归属失败");
    	 String deviceSnListStr = WebUtils.getString(request, "deviceSnListStr");
    	 if(StringTools.isNotBlank(deviceSnListStr)) {
    		 session.setAttribute(WebConstants.SESSION_BELONG_DEVICE_SN_LIST_STR, deviceSnListStr);
    		 result.setCode(DtoConstants.SUCCESS, null);
    	 }
    	 return result;
    }
    
    @Route(value = { "/device/produce/batch/device/belong/set.html" })
    public String setDeviceBelong(HttpServletRequest request,HttpSession session) {
    	String deviceSnListStr = WebUtils.getAttribute(session, WebConstants.SESSION_BELONG_DEVICE_SN_LIST_STR, String.class);
    	if(StringTools.isNotBlank(deviceSnListStr)) {
    		request.setAttribute("deviceSnListStr", deviceSnListStr);
    		String[] temp = deviceSnListStr.split(",");
    		request.setAttribute("deviceCount", temp.length);
    	}
        return "/device/produce/batch/device/belong.html";
    }

    @Route(value = { "/device/produce/batch/device/belong/set.do" })
    public AjaxResult doDeviceSetBelong(HttpServletRequest request,HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "设置归属失败");
        Long userId = WebUtils.getLong(request,"userId");
        Integer strategyType = WebUtils.getInteger(request,"strategyType");
        String deviceSnListStr = WebUtils.getAttribute(session, WebConstants.SESSION_BELONG_DEVICE_SN_LIST_STR, String.class);
    	if(StringTools.isNotBlank(deviceSnListStr)) {
            User user = UserService.self().getById(userId);
            if(user == null){
                result.setMsg("未找到用户信息");
                return result;
            }
           
        	String[] temp = deviceSnListStr.split(",");
        	List<String> deviceSnList = Arrays.asList(temp);
            if(DeviceService.self().setBelong(deviceSnList,user,strategyType)){
                result.setCode(DtoConstants.SUCCESS,null);
                return result;
            }
        }else {
            result.setMsg("参数错误");
        }
        return result;
    }
    
    @Route(value = { "/device/produce/batch/device/belong/remove.html" })
    public String removeDeviceBelong(HttpServletRequest request,HttpSession session) {
    	String deviceSnListStr = WebUtils.getAttribute(session, WebConstants.SESSION_BELONG_DEVICE_SN_LIST_STR, String.class);
    	if(StringTools.isNotBlank(deviceSnListStr)) {
    		request.setAttribute("deviceSnListStr", deviceSnListStr);
    		String[] temp = deviceSnListStr.split(",");
    		request.setAttribute("deviceCount", temp.length);
    	}
        return "/device/produce/batch/device/belong2.html";
    }
    
    @Route(value = { "/device/produce/batch/device/belong/remove.do" })
    public AjaxResult doDeviceRemoveBelong(HttpServletRequest request,HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "移除归属失败");
        String deviceSnListStr = WebUtils.getAttribute(session, WebConstants.SESSION_BELONG_DEVICE_SN_LIST_STR, String.class);
    	if(StringTools.isNotBlank(deviceSnListStr)) {
        	String[] temp = deviceSnListStr.split(",");
        	List<String> deviceSnList = Arrays.asList(temp);
            if(DeviceService.self().removeBelong(deviceSnList)){
                result.setCode(DtoConstants.SUCCESS,null);
                return result;
            }
        }else {
            result.setMsg("参数错误");
        }
        return result;
    }

    @Route(value = { "/device/produce/batch/excel/export.html" })
    public String exportExcel(HttpServletRequest request) {
        request.setAttribute("httpDomain", PropertyTools.get().getString("httpDomain"));
        return "/device/produce/batch/export.html";
    }

    @Route(value = "/device/produce/batch/excel/export.do")
    public void doExportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String[] titles = {"二维码内容","设备序列号"};
        List<Object[]> data = new ArrayList<>();
        String batchId = WebUtils.getString(request,"batchId");
        String httpDomain = WebUtils.getString(request,"httpDomain");
        if(StringTools.isNotBlank(batchId) && StringTools.isNotBlank(httpDomain)){
            DeviceSearch search = new DeviceSearch();
            search.setBatchId(batchId);
            Integer pageNo = 1;
            Integer pageLimit = 300;
            List<Device> deviceList = DeviceService.self().findBySearch(search,pageNo,pageLimit);
            while(deviceList != null && deviceList.size() > 0){
                for(Device device : deviceList){
                    String code = "auto";
                    if(StringTools.isNotBlank(device.getDeviceFunCodes())){
                        if(!device.getDeviceFunCodes().contains(",")){
                            code = device.getDeviceFunCodes().toLowerCase();
                        }
                    }

                    Object[] objects = new Object[2];
                    objects[0] = httpDomain + "/dev/"+code+"/" + device.getDeviceSn();
                    objects[1] = device.getDeviceSn();
                    data.add(objects);
                }
                pageNo = pageNo + 1;
                deviceList = DeviceService.self().findBySearch(search,pageNo,pageLimit);
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String name = format.format(new Date());
        WebUtils.exportExcel(response, name);
        ExcelTools.export(response.getOutputStream(), "设备序列号信息", null, titles, data);
    }

    @Route(value = { "/device/produce/batch/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败，请稍后再试");
        String batchId = WebUtils.getString(request,"batchId");
        try {
            if(DeviceProduceBatchService.self().deleteByBatchId(batchId)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/device/produce/batch/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer page = WebUtils.getInteger(request, "page", 1);

        DeviceProduceBatchSearch search = new DeviceProduceBatchSearch();
        search.setName(term);
        Long total = 0L;
        List<DeviceProduceBatch> list = DeviceProduceBatchService.self().findBySearch(search, page, WebConstants.PAGE_LIMIT);
        if (list != null) {
            for (DeviceProduceBatch deviceProduceBatch : list) {
                SelectResult.Item item = new SelectResult.Item();
                item.setId(deviceProduceBatch.getBatchId());
                item.setText(deviceProduceBatch.getName());
                result.getBody().getData().add(item);
            }
            total += list.size();
        }
        result.getBody().setPage(page);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(total);
        return result;
    }
}
